package mylab.starters.security.config.csrf;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;

/**
 * attention:简单跨域就是GET，HEAD和POST请求，但是POST请求的"Content-Type"只能是application/x-www-form-urlencoded, multipart/form-data 或 text/plain
 * 反之，就是非简单跨域，此跨域有一个预检机制，说直白点，就是会发两次请求，一次OPTIONS请求，一次真正的请求
 */
@Slf4j
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties({CsrfProperties.class})
public class CsrfConfiguration {

    private final CsrfProperties properties;

    @Bean
    public FilterRegistrationBean csrfFilter() {
        CsrfFilter filter = new CsrfFilter(new HttpSessionCsrfTokenRepository());
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(filter);
        registration.setEnabled(properties.isEnabled());
        registration.setUrlPatterns(properties.getUrlPatterns());
        registration.setInitParameters(properties.getInitParameters());
        return registration;
    }


}
